#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Kernel Version Detection and Strategy Mapping System
内核版本检测-策略映射系统

该模块实现：
1. 内核版本动态适配框架
2. 内核特性探测和能力映射
3. 策略选择和优化建议
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

import os
import re
import sys
import json
import platform
import subprocess
import logging
import time
import threading
from collections import OrderedDict, defaultdict
from packaging import version

# Python 2/3 兼容性
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
else:
    string_types = str
    text_type = str


class KernelDetector(object):
    """内核检测器 - 检测系统内核版本和配置"""
    
    def __init__(self):
        self.kernel_info = {}
        self.capabilities = {}
        self.performance_metrics = {
            'operation_counts': defaultdict(int),
            'response_times': [],
            'success_count': 0,
            'failure_count': 0,
            'start_time': time.time(),
            'detection_times': defaultdict(list),
            'strategy_selection_times': defaultdict(list),
            'compatibility_check_times': defaultdict(list),
            'success_rates': defaultdict(list),
            'total_operations': 0,
            'failed_operations': 0
        }
        self._metrics_lock = threading.Lock()
        self._setup_logging()
        self._load_strategy_mappings()
    
    def _setup_logging(self):
        """设置日志记录"""
        try:
            # 尝试使用统一日志系统
            import sys
            import os
            sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'config'))
            from unified_logger import get_logger, LogLevel, LogFormat
            
            log_config = {
                'log_level': LogLevel.INFO.value,
                'log_format': LogFormat.DETAILED.value,
                'enable_console': True,
                'enable_file': False  # 环境检测器不需要文件日志
            }
            
            self.logger = get_logger("environment_detector", log_config)
            
        except ImportError:
            # 回退到传统日志系统
            self.logger = logging.getLogger(__name__)
            if not self.logger.handlers:
                handler = logging.StreamHandler()
                formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
                handler.setFormatter(formatter)
                self.logger.addHandler(handler)
                self.logger.setLevel(logging.INFO)
    
    def _record_performance_metric(self, operation_type, metric_type, value):
        """记录性能指标"""
        try:
            with self._metrics_lock:
                if metric_type == 'execution_time':
                    self.performance_metrics['detection_times'][operation_type].append(value)
                elif metric_type == 'strategy_selection_time':
                    self.performance_metrics['strategy_selection_times'][operation_type].append(value)
                elif metric_type == 'compatibility_check_time':
                    self.performance_metrics['compatibility_check_times'][operation_type].append(value)
                elif metric_type == 'success_rate':
                    self.performance_metrics['success_rates'][operation_type].append(value)
                
                self.performance_metrics['total_operations'] += 1
                
        except Exception as e:
            self.logger.warning(f"性能指标记录失败: {e}")
    
    def _record_operation_result(self, success=True):
        """记录操作结果"""
        try:
            with self._metrics_lock:
                if not success:
                    self.performance_metrics['failed_operations'] += 1
        except Exception as e:
            self.logger.warning(f"操作结果记录失败: {e}")
    
    def detect_kernel_version(self):
        """检测内核版本信息"""
        start_time = time.time()
        try:
            system = platform.system()
            release = platform.release()
            machine = platform.machine()
            
            # 解析版本号
            version_match = re.match(r'(\d+)\.(\d+)\.?(\d*)', release)
            if version_match:
                major = int(version_match.group(1))
                minor = int(version_match.group(2))
                patch = int(version_match.group(3)) if version_match.group(3) else 0
            else:
                self.logger.warning(f"无法解析内核版本: {release}")
                major, minor, patch = 0, 0, 0
            
            self.kernel_info = {
                'system': system,
                'release': release,
                'machine': machine,
                'major_version': major,
                'minor_version': minor,
                'patch_version': patch,
                'distribution': self._detect_distribution(),
                'distro_version': self._get_distro_version()
            }
            
            execution_time = time.time() - start_time
            self._record_performance_metric('kernel_detection', 'execution_time', execution_time)
            self._record_operation_result(success=True)
            
            self.logger.info(f"内核检测成功: {system} {release} (耗时: {execution_time:.3f}s)")
            return self.kernel_info
            
        except (OSError, IOError) as e:
            execution_time = time.time() - start_time
            self._record_performance_metric('kernel_detection', 'execution_time', execution_time)
            self._record_operation_result(success=False)
            error_msg = f"系统信息获取失败: {e}"
            self.logger.error(error_msg)
            raise KernelDetectionError(error_msg)
        except ValueError as e:
            execution_time = time.time() - start_time
            self._record_performance_metric('kernel_detection', 'execution_time', execution_time)
            self._record_operation_result(success=False)
            error_msg = f"版本号解析失败: {e}"
            self.logger.error(error_msg)
            raise KernelDetectionError(error_msg)
        except Exception as e:
            execution_time = time.time() - start_time
            self._record_performance_metric('kernel_detection', 'execution_time', execution_time)
            self._record_operation_result(success=False)
            error_msg = f"内核版本检测失败: {e}"
            self.logger.error(error_msg)
            raise KernelDetectionError(error_msg)

    def _detect_distribution(self):
        """检测Linux发行版"""
        try:
            # 尝试读取 /etc/os-release
            if os.path.exists('/etc/os-release'):
                return self._parse_os_release()
            
            # 备用检测方法
            elif os.path.exists('/etc/redhat-release'):
                return self._parse_redhat_release()
            
            elif os.path.exists('/etc/debian_version'):
                return 'debian'
            
            else:
                self.logger.warning("无法检测到Linux发行版信息")
                return 'unknown'
                
        except (OSError, IOError) as e:
            self.logger.error(f"发行版检测文件读取失败: {e}")
            return 'unknown'
        except Exception as e:
            self.logger.error(f"发行版检测失败: {e}")
            return 'unknown'
    
    def _parse_os_release(self):
        """解析 /etc/os-release 文件"""
        try:
            with open('/etc/os-release', 'r') as f:
                for line in f:
                    if line.startswith('ID='):
                        distro_id = line.split('=')[1].strip().strip('"')
                        return distro_id
            return 'unknown'
        except (OSError, IOError) as e:
            self.logger.error(f"os-release文件读取失败: {e}")
            raise
    
    def _parse_redhat_release(self):
        """解析 RedHat 系列发行版信息"""
        try:
            with open('/etc/redhat-release', 'r') as f:
                content = f.read().strip()
                if 'CentOS' in content:
                    return 'centos'
                elif 'Red Hat' in content:
                    return 'rhel'
                elif 'Fedora' in content:
                    return 'fedora'
                else:
                    return 'redhat'
        except (OSError, IOError) as e:
            self.logger.error(f"redhat-release文件读取失败: {e}")
            raise
    
    def _get_distro_version(self):
        """获取发行版版本"""
        try:
            if os.path.exists('/etc/os-release'):
                with open('/etc/os-release', 'r') as f:
                    for line in f:
                        if line.startswith('VERSION_ID='):
                            version_id = line.split('=')[1].strip().strip('"')
                            return version_id
            return 'unknown'
        except (OSError, IOError) as e:
            self.logger.error(f"发行版版本获取失败: {e}")
            return 'unknown'
        except Exception as e:
            self.logger.error(f"发行版版本解析失败: {e}")
            return 'unknown'

    def _detect_kernel_config(self):
        """检测内核编译配置"""
        config_paths = [
            '/proc/config.gz',
            f"/boot/config-{self.kernel_info.get('release', '')}",
            '/boot/config'
        ]
        
        config_dict = {}
        
        for config_path in config_paths:
            if os.path.exists(config_path):
                try:
                    if config_path.endswith('.gz'):
                        import gzip
                        with gzip.open(config_path, 'rt') as f:
                            config_dict = self._parse_kernel_config(f)
                    else:
                        with open(config_path, 'r') as f:
                            config_dict = self._parse_kernel_config(f)
                    break
                except Exception as e:
                    self.logger.warning(f"无法解析内核配置文件 {config_path}: {e}")
                    continue
        
        return config_dict
    
    def _parse_kernel_config(self, config_file):
        """解析内核配置文件"""
        config_options = {}
        for line in config_file:
            line = line.strip()
            if line.startswith('CONFIG_'):
                if '=' in line:
                    key, value = line.split('=', 1)
                    config_options[key] = value
        
        self.kernel_info['config_options'] = config_options
        return config_options
    
    def analyze_capabilities(self):
        """分析系统能力"""
        try:
            if not self.kernel_info:
                self.detect_kernel_version()
            
            capabilities = {}
            
            # 检测内核编译配置
            kernel_config = self._detect_kernel_config()
            capabilities.update(kernel_config)
            
            # 检查运行时能力
            self._check_runtime_capabilities(capabilities)
            
            # 验证策略兼容性
            self._validate_strategy_compatibility(capabilities)
            
            self.capabilities = capabilities
            return capabilities
            
        except Exception as e:
            self.logger.error(f"能力分析失败: {e}")
            return {}
    
    def _validate_strategy_compatibility(self, capabilities):
        """验证策略与当前环境的兼容性"""
        start_time = time.time()
        try:
            compatibility_results = {}
            
            for operation_type in self.get_available_operation_types():
                strategy = self.get_optimal_strategy(operation_type)
                if strategy:
                    compatibility = self._test_strategy_compatibility(strategy, capabilities)
                    compatibility_results[operation_type] = compatibility
            
            capabilities['strategy_compatibility'] = compatibility_results
            
            execution_time = time.time() - start_time
            self._record_performance_metric('compatibility_validation', 'compatibility_check_time', execution_time)
            
            self.logger.info(f"策略兼容性验证完成，共验证 {len(compatibility_results)} 种策略 (耗时: {execution_time:.3f}s)")
            
        except Exception as e:
            execution_time = time.time() - start_time
            self._record_performance_metric('compatibility_validation', 'compatibility_check_time', execution_time)
            self.logger.error(f"策略兼容性验证失败: {e}")

    def _test_strategy_compatibility(self, strategy, capabilities):
        """测试单个策略的兼容性"""
        try:
            compatibility_score = 0.0
            compatibility_details = {
                'primary_strategy': strategy.get('primary', 'unknown'),
                'fallback_strategy': strategy.get('fallback', 'unknown'),
                'requirements_met': True,
                'missing_requirements': [],
                'compatibility_score': 0.0,
                'recommendations': []
            }
            
            # 检查策略要求
            requirements = strategy.get('requirements', [])
            missing_requirements = []
            
            for req in requirements:
                if not self._check_requirement_availability(req, capabilities):
                    missing_requirements.append(req)
                    compatibility_details['requirements_met'] = False
            
            compatibility_details['missing_requirements'] = missing_requirements
            
            # 计算兼容性分数
            if not missing_requirements:
                compatibility_score = 1.0  # 完全兼容
            else:
                # 根据缺失要求的数量计算分数
                compatibility_score = max(0.0, 1.0 - (len(missing_requirements) / max(len(requirements), 1)))
            
            # 添加环境特定的兼容性检查
            compatibility_score = self._adjust_compatibility_score(strategy, capabilities, compatibility_score)
            
            compatibility_details['compatibility_score'] = compatibility_score
            
            # 生成建议
            if compatibility_score < 0.8:
                compatibility_details['recommendations'] = self._generate_compatibility_recommendations(
                    strategy, missing_requirements, capabilities
                )
            
            return compatibility_details
            
        except Exception as e:
            self.logger.error(f"策略兼容性测试失败: {e}")
            return {
                'primary_strategy': strategy.get('primary', 'unknown'),
                'compatibility_score': 0.0,
                'error': str(e)
            }
    
    def _check_requirement_availability(self, requirement, capabilities):
        """检查特定要求是否满足"""
        try:
            # 检查内核配置要求
            if requirement.startswith('CONFIG_'):
                return capabilities.get(requirement, False)
            
            # 检查内核版本要求
            if requirement.startswith('kernel_'):
                required_version = requirement.replace('kernel_', '').replace('+', '')
                current_version = f"{self.kernel_info.get('major_version', 0)}.{self.kernel_info.get('minor_version', 0)}"
                try:
                    return version.parse(current_version) >= version.parse(required_version)
                except version.InvalidVersion:
                    return False
            
            # 检查系统调用可用性
            if requirement.startswith('syscall_'):
                return self._check_syscall_availability(requirement.replace('syscall_', ''))
            
            # 检查文件系统特性
            if requirement.startswith('fs_'):
                return self._check_filesystem_feature(requirement.replace('fs_', ''))
            
            # 检查权限要求
            if requirement.startswith('perm_'):
                return self._check_permission_requirement(requirement.replace('perm_', ''))
            
            return True
            
        except Exception as e:
            self.logger.warning(f"要求检查失败 {requirement}: {e}")
            return False
    
    def _check_syscall_availability(self, syscall_name):
        """检查系统调用是否可用"""
        try:
            # 检查常见系统调用
            syscall_checks = {
                'memfd_create': lambda: self._test_memfd_create(),
                'process_vm_readv': lambda: self._test_process_vm_readv(),
                'ptrace': lambda: self._test_ptrace_availability(),
                'prctl': lambda: self._test_prctl_availability()
            }
            
            if syscall_name in syscall_checks:
                return syscall_checks[syscall_name]()
            
            return True  # 默认假设可用
            
        except Exception as e:
            self.logger.warning(f"系统调用检查失败 {syscall_name}: {e}")
            return False
    
    def _test_memfd_create(self):
        """测试 memfd_create 系统调用"""
        try:
            import ctypes
            import ctypes.util
            
            libc_name = ctypes.util.find_library('c')
            if not libc_name:
                return False
            
            libc = ctypes.CDLL(libc_name)
            
            # 检查是否有 memfd_create 函数
            if hasattr(libc, 'memfd_create'):
                return True
            
            # 尝试通过系统调用号调用
            try:
                import os
                # 在 Linux 上尝试创建一个测试 memfd
                fd = os.memfd_create("test", 0)
                os.close(fd)
                return True
            except (AttributeError, OSError):
                return False
                
        except Exception:
            return False
    
    def _test_process_vm_readv(self):
        """测试 process_vm_readv 系统调用"""
        try:
            import ctypes
            import ctypes.util
            
            libc_name = ctypes.util.find_library('c')
            if not libc_name:
                return False
            
            libc = ctypes.CDLL(libc_name)
            return hasattr(libc, 'process_vm_readv')
            
        except Exception:
            return False
    
    def _test_ptrace_availability(self):
        """测试 ptrace 可用性"""
        try:
            # 检查 ptrace 是否被禁用
            ptrace_scope_file = '/proc/sys/kernel/yama/ptrace_scope'
            if os.path.exists(ptrace_scope_file):
                with open(ptrace_scope_file, 'r') as f:
                    ptrace_scope = int(f.read().strip())
                    # 0: 传统 ptrace 行为
                    # 1: 限制 ptrace 到直接子进程
                    # 2: 只有 CAP_SYS_PTRACE 能力的进程可以使用 ptrace
                    # 3: 完全禁用 ptrace
                    return ptrace_scope < 3
            
            return True  # 如果文件不存在，假设可用
            
        except Exception:
            return False
    
    def _test_prctl_availability(self):
        """测试 prctl 系统调用"""
        try:
            import ctypes
            import ctypes.util
            
            libc_name = ctypes.util.find_library('c')
            if not libc_name:
                return False
            
            libc = ctypes.CDLL(libc_name)
            return hasattr(libc, 'prctl')
            
        except Exception:
            return False
    
    def _check_filesystem_feature(self, feature):
        """检查文件系统特性"""
        try:
            fs_checks = {
                'tmpfs': lambda: os.path.exists('/dev/shm'),
                'procfs': lambda: os.path.exists('/proc'),
                'sysfs': lambda: os.path.exists('/sys'),
                'debugfs': lambda: os.path.exists('/sys/kernel/debug'),
                'securityfs': lambda: os.path.exists('/sys/kernel/security')
            }
            
            if feature in fs_checks:
                return fs_checks[feature]()
            
            return True
            
        except Exception as e:
            self.logger.warning(f"文件系统特性检查失败 {feature}: {e}")
            return False
    
    def _check_permission_requirement(self, permission):
        """检查权限要求"""
        try:
            perm_checks = {
                'root': lambda: os.geteuid() == 0,
                'sudo': lambda: self._check_sudo_availability(),
                'cap_sys_admin': lambda: self._check_capability('CAP_SYS_ADMIN'),
                'cap_sys_ptrace': lambda: self._check_capability('CAP_SYS_PTRACE')
            }
            
            if permission in perm_checks:
                return perm_checks[permission]()
            
            return True
            
        except Exception as e:
            self.logger.warning(f"权限检查失败 {permission}: {e}")
            return False
    
    def _check_sudo_availability(self):
        """检查 sudo 可用性"""
        try:
            result = subprocess.run(['sudo', '-n', 'true'], 
                                  capture_output=True, 
                                  timeout=5)
            return result.returncode == 0
        except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
            return False
    
    def _check_capability(self, capability):
        """检查进程能力"""
        try:
            # 尝试读取当前进程的能力
            with open('/proc/self/status', 'r') as f:
                for line in f:
                    if line.startswith('CapEff:'):
                        cap_eff = int(line.split()[1], 16)
                        # 这里需要根据具体的能力位进行检查
                        # 简化实现，假设有效
                        return cap_eff > 0
            return False
        except Exception:
            return False
    
    def _adjust_compatibility_score(self, strategy, capabilities, base_score):
        """根据环境特性调整兼容性分数"""
        try:
            adjusted_score = base_score
            
            # 根据内核版本调整
            kernel_version = f"{self.kernel_info.get('major_version', 0)}.{self.kernel_info.get('minor_version', 0)}"
            
            # 较新的内核通常有更好的兼容性
            try:
                if version.parse(kernel_version) >= version.parse("5.0"):
                    adjusted_score += 0.1
                elif version.parse(kernel_version) >= version.parse("4.0"):
                    adjusted_score += 0.05
            except version.InvalidVersion:
                pass
            
            # 根据发行版调整
            distribution = self.kernel_info.get('distribution', 'unknown')
            if distribution in ['ubuntu', 'debian', 'centos', 'rhel']:
                adjusted_score += 0.05  # 主流发行版通常兼容性更好
            
            # 根据安全特性调整
            if capabilities.get('kernel_kptr_restrict', 0) > 1:
                adjusted_score -= 0.1  # 严格的安全设置可能影响兼容性
            
            return min(1.0, max(0.0, adjusted_score))
            
        except Exception as e:
            self.logger.warning(f"兼容性分数调整失败: {e}")
            return base_score
    
    def _generate_compatibility_recommendations(self, strategy, missing_requirements, capabilities):
        """生成兼容性改进建议"""
        try:
            recommendations = []
            
            for req in missing_requirements:
                if req.startswith('CONFIG_'):
                    recommendations.append(f"重新编译内核并启用 {req} 配置选项")
                elif req.startswith('kernel_'):
                    required_version = req.replace('kernel_', '').replace('+', '')
                    recommendations.append(f"升级内核到版本 {required_version} 或更高")
                elif req.startswith('syscall_'):
                    syscall = req.replace('syscall_', '')
                    recommendations.append(f"确保系统支持 {syscall} 系统调用")
                elif req.startswith('perm_'):
                    perm = req.replace('perm_', '')
                    recommendations.append(f"获取 {perm} 权限")
            
            # 添加通用建议
            if strategy.get('fallback'):
                recommendations.append(f"考虑使用备用策略: {strategy['fallback']}")
            
            return recommendations
            
        except Exception as e:
            self.logger.error(f"建议生成失败: {e}")
            return ["请检查系统配置和权限设置"]

    def _check_runtime_capabilities(self, capabilities):
        """检查运行时能力"""
        try:
            # 检查 /proc/sys/kernel 下的配置
            kernel_configs = {
                'kptr_restrict': '/proc/sys/kernel/kptr_restrict',
                'dmesg_restrict': '/proc/sys/kernel/dmesg_restrict',
                'perf_event_paranoid': '/proc/sys/kernel/perf_event_paranoid'
            }
            
            for config_name, config_path in kernel_configs.items():
                try:
                    if os.path.exists(config_path):
                        with open(config_path, 'r') as f:
                            value = f.read().strip()
                            capabilities[f'kernel_{config_name}'] = int(value) if value.isdigit() else value
                except (OSError, IOError) as e:
                    self.logger.warning(f"无法读取内核配置 {config_name}: {e}")
                except ValueError as e:
                    self.logger.warning(f"内核配置值解析失败 {config_name}: {e}")
            
            return capabilities
            
        except Exception as e:
            self.logger.error(f"运行时能力检查失败: {e}")
            return capabilities
    
    def _load_strategy_mappings(self):
        """加载策略映射配置"""
        self.strategy_map = {
            # 无文件执行策略
            'fileless_execution': {
                'kernel_5.3+': {
                    'primary': 'memfd_secret',
                    'fallback': 'memfd_create',
                    'description': '使用 memfd_secret 实现更隐蔽的无文件执行',
                    'requirements': ['CONFIG_MEMFD_CREATE', 'CONFIG_TMPFS'],
                    'success_rate': 0.95
                },
                'kernel_3.17+': {
                    'primary': 'memfd_create',
                    'fallback': 'tmpfs_unlink',
                    'description': '使用 memfd_create 创建匿名文件描述符',
                    'requirements': ['CONFIG_MEMFD_CREATE'],
                    'success_rate': 0.90
                },
                'kernel_legacy': {
                    'primary': 'tmpfs_unlink',
                    'fallback': 'dev_shm',
                    'description': '使用 tmpfs + unlink 组合方案',
                    'requirements': ['CONFIG_TMPFS'],
                    'success_rate': 0.75
                }
            },
            
            # 进程注入策略
            'process_injection': {
                'kernel_4.1+': {
                    'primary': 'ptrace_seize',
                    'fallback': 'ptrace_attach',
                    'description': '使用 PTRACE_SEIZE 进行更隐蔽的进程注入',
                    'requirements': ['CONFIG_PTRACE'],
                    'success_rate': 0.88
                },
                'kernel_legacy': {
                    'primary': 'ptrace_attach',
                    'fallback': 'proc_mem',
                    'description': '使用传统 PTRACE_ATTACH 方法',
                    'requirements': ['CONFIG_PTRACE'],
                    'success_rate': 0.80
                }
            },
            
            # 权限提升策略
            'privilege_escalation': {
                'kernel_3.8+': {
                    'primary': 'user_namespace',
                    'fallback': 'setuid_exploit',
                    'description': '利用用户命名空间进行权限提升',
                    'requirements': ['CONFIG_USER_NS'],
                    'success_rate': 0.85
                },
                'kernel_legacy': {
                    'primary': 'setuid_exploit',
                    'fallback': 'kernel_exploit',
                    'description': '使用传统提权漏洞',
                    'requirements': [],
                    'success_rate': 0.70
                }
            },
            
            # 痕迹清理策略
            'trace_cleaning': {
                'kernel_4.5+': {
                    'primary': 'cgroup_v2_hide',
                    'fallback': 'proc_hide',
                    'description': '使用 cgroup v2 隐藏进程',
                    'requirements': ['CONFIG_CGROUPS', 'CONFIG_CGROUP_V2'],
                    'success_rate': 0.92
                },
                'kernel_legacy': {
                    'primary': 'proc_hide',
                    'fallback': 'log_rotation',
                    'description': '使用传统进程隐藏技术',
                    'requirements': ['CONFIG_PROC_FS'],
                    'success_rate': 0.78
                }
            }
        }
    
    def get_available_operation_types(self):
        """动态获取可用的操作类型"""
        return list(self.strategy_map.keys())
    
    def get_optimal_strategy(self, operation_type):
        """获取最优策略"""
        start_time = time.time()
        
        if operation_type not in self.strategy_map:
            self._record_performance_metric('strategy_selection', 'strategy_selection_time', time.time() - start_time)
            self._record_operation_result(success=False)
            self.logger.warning(f"未知的操作类型: {operation_type}")
            return None
        
        try:
            # 使用packaging库进行更准确的版本比较
            current_version = f"{self.kernel_info.get('major_version', 0)}.{self.kernel_info.get('minor_version', 0)}.{self.kernel_info.get('patch_version', 0)}"
            
            strategies = self.strategy_map[operation_type]
            
            # 根据内核版本选择策略
            if version.parse(current_version) >= version.parse("5.3.0"):
                strategy = strategies.get('kernel_5.3+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("4.5.0"):
                strategy = strategies.get('kernel_4.5+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("4.1.0"):
                strategy = strategies.get('kernel_4.1+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("3.17.0"):
                strategy = strategies.get('kernel_3.17+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("3.8.0"):
                strategy = strategies.get('kernel_3.8+', strategies.get('kernel_legacy'))
            else:
                strategy = strategies.get('kernel_legacy')
            
            # 验证策略可用性
            if strategy and self._validate_strategy_requirements(strategy):
                execution_time = time.time() - start_time
                self._record_performance_metric(operation_type, 'strategy_selection_time', execution_time)
                self._record_operation_result(success=True)
                
                # 记录策略成功率（基于历史数据或预设值）
                success_rate = strategy.get('success_rate', 0.8)
                self._record_performance_metric(operation_type, 'success_rate', success_rate)
                
                self.logger.info(f"为 {operation_type} 选择策略: {strategy['primary']} (耗时: {execution_time:.3f}s, 成功率: {success_rate:.2%})")
                return strategy
            else:
                # 如果主策略不可用，尝试回退策略
                self.logger.warning(f"主策略不可用，尝试回退策略: {operation_type}")
                fallback_strategy = self._get_fallback_strategy(operation_type)
                
                execution_time = time.time() - start_time
                self._record_performance_metric(operation_type, 'strategy_selection_time', execution_time)
                
                if fallback_strategy:
                    self._record_operation_result(success=True)
                    # 回退策略通常成功率较低
                    success_rate = fallback_strategy.get('success_rate', 0.6)
                    self._record_performance_metric(operation_type, 'success_rate', success_rate)
                else:
                    self._record_operation_result(success=False)
                
                return fallback_strategy
                 
        except version.InvalidVersion as e:
            execution_time = time.time() - start_time
            self._record_performance_metric(operation_type, 'strategy_selection_time', execution_time)
            self._record_operation_result(success=False)
            error_msg = f"版本格式无效: {e}"
            self.logger.error(error_msg)
            raise StrategyValidationError(error_msg)
        except KeyError as e:
            execution_time = time.time() - start_time
            self._record_performance_metric(operation_type, 'strategy_selection_time', execution_time)
            self._record_operation_result(success=False)
            error_msg = f"策略配置缺失: {e}"
            self.logger.error(error_msg)
            raise StrategyValidationError(error_msg)
        except Exception as e:
            execution_time = time.time() - start_time
            self._record_performance_metric(operation_type, 'strategy_selection_time', execution_time)
            self._record_operation_result(success=False)
            error_msg = f"策略选择失败: {e}"
            self.logger.error(error_msg)
            # 返回基础策略而不是抛出异常
            return strategies.get('kernel_legacy')
    
    def _load_strategy_mappings(self):
        """加载策略映射配置"""
        self.strategy_map = {
            # 无文件执行策略
            'fileless_execution': {
                'kernel_5.3+': {
                    'primary': 'memfd_secret',
                    'fallback': 'memfd_create',
                    'description': '使用 memfd_secret 实现更隐蔽的无文件执行',
                    'requirements': ['CONFIG_MEMFD_CREATE', 'CONFIG_TMPFS'],
                    'success_rate': 0.95
                },
                'kernel_3.17+': {
                    'primary': 'memfd_create',
                    'fallback': 'tmpfs_unlink',
                    'description': '使用 memfd_create 创建匿名文件描述符',
                    'requirements': ['CONFIG_MEMFD_CREATE'],
                    'success_rate': 0.90
                },
                'kernel_legacy': {
                    'primary': 'tmpfs_unlink',
                    'fallback': 'dev_shm',
                    'description': '使用 tmpfs + unlink 组合方案',
                    'requirements': ['CONFIG_TMPFS'],
                    'success_rate': 0.75
                }
            },
            
            # 进程注入策略
            'process_injection': {
                'kernel_4.1+': {
                    'primary': 'ptrace_seize',
                    'fallback': 'ptrace_attach',
                    'description': '使用 PTRACE_SEIZE 进行更隐蔽的进程注入',
                    'requirements': ['CONFIG_PTRACE'],
                    'success_rate': 0.88
                },
                'kernel_legacy': {
                    'primary': 'ptrace_attach',
                    'fallback': 'proc_mem',
                    'description': '使用传统 PTRACE_ATTACH 方法',
                    'requirements': ['CONFIG_PTRACE'],
                    'success_rate': 0.80
                }
            },
            
            # 权限提升策略
            'privilege_escalation': {
                'kernel_3.8+': {
                    'primary': 'user_namespace',
                    'fallback': 'setuid_exploit',
                    'description': '利用用户命名空间进行权限提升',
                    'requirements': ['CONFIG_USER_NS'],
                    'success_rate': 0.85
                },
                'kernel_legacy': {
                    'primary': 'setuid_exploit',
                    'fallback': 'kernel_exploit',
                    'description': '使用传统提权漏洞',
                    'requirements': [],
                    'success_rate': 0.70
                }
            },
            
            # 痕迹清理策略
            'trace_cleaning': {
                'kernel_4.5+': {
                    'primary': 'cgroup_v2_hide',
                    'fallback': 'proc_hide',
                    'description': '使用 cgroup v2 隐藏进程',
                    'requirements': ['CONFIG_CGROUPS', 'CONFIG_CGROUP_V2'],
                    'success_rate': 0.92
                },
                'kernel_legacy': {
                    'primary': 'proc_hide',
                    'fallback': 'log_rotation',
                    'description': '使用传统进程隐藏技术',
                    'requirements': ['CONFIG_PROC_FS'],
                    'success_rate': 0.78
                }
            }
        }
    
    def get_available_operation_types(self):
        """动态获取可用的操作类型"""
        return list(self.strategy_map.keys())
    
    def get_optimal_strategy(self, operation_type):
        """获取最优策略"""
        if operation_type not in self.strategy_map:
            self.logger.warning(f"未知的操作类型: {operation_type}")
            return None
        
        try:
            # 使用packaging库进行更准确的版本比较
            current_version = f"{self.kernel_info.get('major_version', 0)}.{self.kernel_info.get('minor_version', 0)}.{self.kernel_info.get('patch_version', 0)}"
            
            strategies = self.strategy_map[operation_type]
            
            # 根据内核版本选择策略
            if version.parse(current_version) >= version.parse("5.3.0"):
                strategy = strategies.get('kernel_5.3+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("4.5.0"):
                strategy = strategies.get('kernel_4.5+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("4.1.0"):
                strategy = strategies.get('kernel_4.1+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("3.17.0"):
                strategy = strategies.get('kernel_3.17+', strategies.get('kernel_legacy'))
            elif version.parse(current_version) >= version.parse("3.8.0"):
                strategy = strategies.get('kernel_3.8+', strategies.get('kernel_legacy'))
            else:
                strategy = strategies.get('kernel_legacy')
            
            # 验证策略可用性
            if strategy and self._validate_strategy_requirements(strategy):
                self.logger.info(f"为 {operation_type} 选择策略: {strategy['primary']}")
                return strategy
            else:
                # 如果主策略不可用，尝试回退策略
                self.logger.warning(f"主策略不可用，尝试回退策略: {operation_type}")
                return self._get_fallback_strategy(operation_type)
                 
        except version.InvalidVersion as e:
            error_msg = f"版本格式无效: {e}"
            self.logger.error(error_msg)
            raise StrategyValidationError(error_msg)
        except KeyError as e:
            error_msg = f"策略配置缺失: {e}"
            self.logger.error(error_msg)
            raise StrategyValidationError(error_msg)
        except Exception as e:
            error_msg = f"策略选择失败: {e}"
            self.logger.error(error_msg)
            # 返回基础策略而不是抛出异常
            return strategies.get('kernel_legacy')
    
    def _validate_strategy_requirements(self, strategy):
        """验证策略的系统要求"""
        try:
            requirements = strategy.get('requirements', [])
            if not requirements:
                return True
            
            # 检查内核配置要求
            missing_requirements = []
            for req in requirements:
                if not self._check_kernel_config_option(req):
                    missing_requirements.append(req)
            
            if missing_requirements:
                self.logger.warning(f"策略要求未满足: {missing_requirements}")
                return False
            
            return True
            
        except Exception as e:
            self.logger.error(f"策略验证失败: {e}")
            return False
    
    def _check_kernel_config_option(self, option):
        """检查内核配置选项是否启用"""
        try:
            config_files = ['/proc/config.gz', '/boot/config-' + platform.release()]
            
            for config_file in config_files:
                if os.path.exists(config_file):
                    try:
                        if config_file.endswith('.gz'):
                            import gzip
                            with gzip.open(config_file, 'rt') as f:
                                content = f.read()
                        else:
                            with open(config_file, 'r') as f:
                                content = f.read()
                        
                        # 查找配置选项
                        if f"{option}=y" in content or f"{option}=m" in content:
                            return True
                    except (OSError, IOError) as e:
                        self.logger.warning(f"配置文件读取失败 {config_file}: {e}")
                        continue
                    except Exception as e:
                        self.logger.warning(f"配置文件解析失败 {config_file}: {e}")
                        continue
            
            return False
            
        except ImportError as e:
            self.logger.error(f"gzip模块导入失败: {e}")
            return False
        except Exception as e:
            self.logger.error(f"内核配置检查失败: {e}")
            return False
    
    def _get_fallback_strategy(self, operation_type):
        """获取回退策略"""
        try:
            strategies = self.strategy_map.get(operation_type, {})
            fallback = strategies.get('kernel_legacy')
            
            if fallback:
                self.logger.info(f"使用回退策略: {fallback['primary']}")
            else:
                self.logger.warning(f"无可用的回退策略: {operation_type}")
            
            return fallback
            
        except Exception as e:
            self.logger.error(f"回退策略获取失败: {e}")
            return None

    def generate_capabilities_json(self, output_path=None):
        """生成内核能力配置文件"""
        try:
            if not self.kernel_info or not self.capabilities:
                raise ConfigurationError("请先运行 detect_kernel_version() 和 analyze_capabilities()")
            
            config_data = {
                'kernel_info': self.kernel_info,
                'capabilities': self.capabilities,
                'timestamp': self._get_timestamp()
            }
            
            if output_path:
                with open(output_path, 'w') as f:
                    json.dump(config_data, f, indent=2, ensure_ascii=False)
                self.logger.info(f"配置文件已保存到: {output_path}")
            
            return config_data
            
        except (OSError, IOError) as e:
            error_msg = f"配置文件写入失败: {e}"
            self.logger.error(error_msg)
            raise ConfigurationError(error_msg)
        except (ValueError, TypeError) as e:  # JSONEncodeError在Python 2中不存在
            error_msg = f"JSON序列化失败: {e}"
            self.logger.error(error_msg)
            raise ConfigurationError(error_msg)
        except Exception as e:
            error_msg = f"配置生成失败: {e}"
            self.logger.error(error_msg)
            raise ConfigurationError(error_msg)

    def _get_timestamp(self):
        """获取当前时间戳"""
        return time.time()

    def get_performance_summary(self):
        """获取性能摘要"""
        summary = {
            'total_operations': sum(self.performance_metrics['operation_counts'].values()),
            'success_rate': 0.0,
            'average_response_time': 0.0,
            'operation_breakdown': dict(self.performance_metrics['operation_counts']),
            'timing_stats': {}
        }
        
        # 计算成功率
        total_ops = self.performance_metrics['success_count'] + self.performance_metrics['failure_count']
        if total_ops > 0:
            summary['success_rate'] = (self.performance_metrics['success_count'] / total_ops) * 100
        
        # 计算平均响应时间
        response_times = self.performance_metrics['response_times']
        if response_times:
            summary['average_response_time'] = sum(response_times) / len(response_times)
            summary['timing_stats'] = {
                'min': min(response_times),
                'max': max(response_times),
                'count': len(response_times)
            }
        
        return summary

    def print_performance_report(self):
        """打印性能报告"""
        summary = self.get_performance_summary()
        
        print("\n" + "="*50)
        print("                性能报告")
        print("="*50)
        print(f"总操作数: {summary['total_operations']}")
        print(f"成功率: {summary['success_rate']:.1f}%")
        print(f"平均响应时间: {summary['average_response_time']:.3f}秒")
        
        if summary['timing_stats']:
            stats = summary['timing_stats']
            print(f"响应时间统计: 最小={stats['min']:.3f}s, 最大={stats['max']:.3f}s, 样本数={stats['count']}")
        
        print("\n操作类型分布:")
        for op_type, count in summary['operation_breakdown'].items():
            print(f"  {op_type}: {count}")
        
        print("="*50)

    def reset_performance_metrics(self):
        """重置性能指标"""
        self.performance_metrics = {
            'operation_counts': defaultdict(int),
            'response_times': [],
            'success_count': 0,
            'failure_count': 0,
            'start_time': time.time()
        }
        self.logger.info("性能指标已重置")


class EnvironmentAnalyzer(object):
    """环境分析器"""
    
    def __init__(self):
        self.detector = KernelDetector()
        self.analysis_result = {}
    
    def full_analysis(self):
        """完整环境分析"""
        print("[*] 开始环境分析...")
        
        # 检测内核版本
        kernel_info = self.detector.detect_kernel_version()
        print(f"[+] 内核版本: {kernel_info.get('version_string', 'Unknown')}")
        
        # 分析能力
        capabilities = self.detector.analyze_capabilities()
        print(f"[+] 检测到 {len([k for k, v in capabilities.items() if v])} 项可用特性")
        
        # 生成配置文件
        config_path = self.detector.generate_capabilities_json()
        
        self.analysis_result = {
            'kernel_info': kernel_info,
            'capabilities': capabilities,
            'config_path': config_path
        }
        
        return self.analysis_result
    
    def get_strategy_recommendation(self, operation_type):
        """获取策略推荐"""
        return self.detector.get_optimal_strategy(operation_type)
    
    def print_analysis_summary(self):
        """打印分析摘要"""
        if not self.analysis_result:
            print("[!] 请先运行 full_analysis()")
            return
        
        kernel_info = self.analysis_result['kernel_info']
        capabilities = self.analysis_result['capabilities']
        
        print("\n" + "="*60)
        print("                  内核环境分析报告")
        print("="*60)
        print(f"系统: {kernel_info.get('system', 'Unknown')}")
        print(f"内核版本: {kernel_info.get('release', 'Unknown')}")
        print(f"发行版: {kernel_info.get('distribution', 'Unknown')} {kernel_info.get('distro_version', '')}")
        print(f"架构: {kernel_info.get('machine', 'Unknown')}")
        
        print("\n可用特性:")
        for feature, available in capabilities.items():
            status = "✓" if available else "✗"
            print(f"  {status} {feature}")
        
        print("\n策略推荐:")
        # 动态获取操作类型而不是硬编码
        operation_types = self.detector.get_available_operation_types()
        for operation_type in operation_types:
            strategy = self.detector.get_optimal_strategy(operation_type)
            if strategy:
                success_rate = strategy.get('success_rate', 0) * 100
                print(f"  {operation_type}: {strategy['primary']} ({strategy['description']}) - 成功率: {success_rate:.1f}%")
            else:
                print(f"  {operation_type}: 无可用策略")
        
        print("="*60)


def main():
    """主函数 - 用于测试"""
    analyzer = EnvironmentAnalyzer()
    analyzer.full_analysis()
    analyzer.print_analysis_summary()


if __name__ == "__main__":
    main()


# 自定义异常类
class KernelDetectionError(Exception):
    """内核检测相关异常"""
    pass

class StrategyValidationError(Exception):
    """策略验证相关异常"""
    pass

class ConfigurationError(Exception):
    """配置相关异常"""
    pass